package com.scalar.chiptrack.operations.reports.actionCommands;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.commons.ExcelColumnProperties;

/**
 * User: KP
 * Date: Oct 25, 2006
 * Time: 2:08:54 PM
*/
public class DataDumpReportActionCommand extends ActionCommand
{
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String action           = request.getParameter( "action" );
        String baseProductId    = request.getParameter( "baseProductId" );
        ArrayList lotInfoList = null;
        Workbook workbook = null;
        String fileName = "";
        
        HashMap<String, String> errors = ( HashMap<String, String> ) request.getAttribute ( ERROR_MESSAGES );
        try
        {
            if( DUMP_REPORT_INVENTORY_COST_ACTION.equalsIgnoreCase( action ) )
            {
                int baseProductIdInt = -1;
                try
                {
                    baseProductIdInt = Integer.parseInt( baseProductId );
                }
                catch( NumberFormatException nfe ){ }

                lotInfoList = DataDumpReportsDAO.getInventoryCostReport( null,  baseProductIdInt );
                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Inventory Cost Report",null,null,null );
                fileName = "InventoryCostReport_" + DateUtil.getTimeStamp() ;
            }
            else if( DUMP_REPORT_WIP_INVENTORY_INFO_ACTION.equalsIgnoreCase( action ) )
            {
                String reportType   = request.getParameter( "prompt12" );

                if ( "intransit".equalsIgnoreCase( reportType ) )
                {
                    String processType      = request.getParameter( "prompt0" );
                    String processstepIds   = request.getParameter( "prompt1" );
                    String baseProductIds   = request.getParameter( "prompt2" );
                    String vendor           = request.getParameter( "prompt3" );
                    String fromDate         = request.getParameter( "prompt4" );
                    String toDate           = request.getParameter( "prompt5" );
                    String searchPartNo     = request.getParameter( "prompt6" );
                    String category         = request.getParameter( "prompt7" );
                    String status           = request.getParameter( "prompt8" );
                    String reportFrom       = request.getParameter( "prompt9" );
                    String reportFormat     = request.getParameter( "prompt10" );
                    String defaultPrompt    = request.getParameter( "prompt11" );

                    lotInfoList = DataDumpReportsDAO.getShipmentRecords ( null, processType, processstepIds, baseProductIds, vendor, fromDate, toDate, searchPartNo, category, status, reportFrom, reportFormat, defaultPrompt );

                    workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Wip Intransit Report", null,null,null );
                    fileName = "WipInTransitReport_" + DateUtil.getTimeStamp() ;
                }
                else
                {
                    if( "discrepancy".equalsIgnoreCase( reportType ) )
                    {
                        String processType      = request.getParameter( "prompt0" );
                        String processstepIds   = request.getParameter( "prompt1" );
                        String vendor           = request.getParameter( "prompt2" );
                        String asofdate         = request.getParameter( "prompt3" );
                        String searchPartNo     = request.getParameter( "prompt4" );
                        String reportFormat     = request.getParameter( "prompt5" );
                        String defaultPrompt    = request.getParameter( "prompt6" );

                        lotInfoList = DataDumpReportsDAO.getDiscrepancyRecords ( null,  processType, processstepIds, vendor, asofdate, searchPartNo, reportFormat, defaultPrompt );

                        workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Discrepancy Report",null,null,null );
                        fileName = "DiscrepancyReport_" + DateUtil.getTimeStamp() ;
                    }
                    else
                    {
                        Map<String, String> paramMap = new HashMap<String, String>();
                        paramMap.put ( "processType", request.getParameter( "prompt0" ) );
                        paramMap.put ( "psIds", request.getParameter( "prompt1" ) );
                        paramMap.put ( "vendor", request.getParameter( "prompt2" ) );
                        paramMap.put ( "lotCategory", request.getParameter( "prompt3" ) );
                        paramMap.put ( "asOfDate", request.getParameter( "prompt4" ) );
                        paramMap.put ( "status", request.getParameter( "prompt5" ) );
                        paramMap.put ( "reportType", request.getParameter( "prompt6" ) );
                        paramMap.put ( "searchPartNo", request.getParameter( "prompt7" ) );
                        paramMap.put ( "defaultPrompt", request.getParameter( "prompt8" ) );

                        //lotInfoList = DataDumpReportsDAO.getWipInventoryInfoReport ( null,  processType, psIds, vendor, lotCategory, asOfDate, status, radioOpt, searchPartNo, defaultPrompt );
                        //workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Wip Inventory Info Report" );
                        workbook = DataDumpReportsDAO.getWipInventoryInfoReport ( null, paramMap ); 
                        fileName = "WipInventoryInfoReport_" + DateUtil.getTimeStamp() ;
                    }
                }
            }
            else if( DUMP_REPORT_CREDIT_DEBIT_REPORT_ACTION.equalsIgnoreCase( action ) )
            {
                String customerIds  = request.getParameter( "prompt0" );
                String productIds   = request.getParameter( "prompt1" );
                String liType       = request.getParameter( "prompt2" );
                String status       = request.getParameter( "prompt3" );
                String fromDate     = request.getParameter( "prompt4" );
                String toDate       = request.getParameter( "prompt5" );
                String reportType   = request.getParameter( "prompt6" );
                String defaultPrompt = request.getParameter( "prompt7" );

                lotInfoList = DataDumpReportsDAO.getCreditDebitNoteReportInfo ( null,  customerIds, productIds, liType,status, fromDate, toDate, reportType, defaultPrompt);

                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Credit Debit Note Report", null,null,null );
                fileName = "CreditDebitNoteReport_" + DateUtil.getTimeStamp() ;
            }
            else if( DUMP_REPORT_COST_CODES_REPORT_ACTION.equalsIgnoreCase( action ) )
            {
                String year  = request.getParameter( "year" );
                String quater   = request.getParameter( "quater" );

                lotInfoList = DataDumpReportsDAO.getCostCodesInfoReport ( null,  year, quater );

                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Cost Codes Report", null,null,null );
                fileName = "CostCodesReport_" + DateUtil.getTimeStamp() ;
            }
            else if( DUMP_REPORT_COST_VARIANCE_REPORT_ACTION.equalsIgnoreCase( action ) )
            {
                String date1        = request.getParameter( "date1" );
                String date2        = request.getParameter( "date2" );
                String defaultPrompt= request.getParameter( "timestamp" );

                lotInfoList = DataDumpReportsDAO.getCostCodeVarianceReport ( null,  date1, date2, defaultPrompt );

                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Cost Variance Report", "#,##0" );
                fileName = "CostVarianceReport_" + DateUtil.getTimeStamp() ;
            }
            else if( DUMP_REPORT_CUMM_YIELD_REPORT_ACTION.equalsIgnoreCase( action ) )
            {

                lotInfoList = DataDumpReportsDAO.getCummYieldReport ( null,  Integer.parseInt(baseProductId) );

                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Cumm Yield Report", null, null, null );
                fileName = "CummYieldReport.xls";
            }

            else if (DUMP_REPORT_INVENTORY_SUMMARY_ACTION.equalsIgnoreCase( action ))
            {
                String productId      = request.getParameter( "prompt0" );
                String lotCategory    = request.getParameter( "prompt1" );
                String vendor         = request.getParameter( "prompt2" );
                String status         = request.getParameter( "prompt3" );
                String asOfDate       = request.getParameter( "prompt4" );
                String defaultPrompt  = request.getParameter( "prompt5" );
                String psTypes  = request.getParameter( "prompt6" );

                //lotInfoList = DataDumpReportsDAO.getInventorySummaryReportInfo ( null,  productId, lotCategory, vendor, status, asOfDate, defaultPrompt);
                lotInfoList = DataDumpReportsDAO.getInventorySummaryReport ( null,  productId, lotCategory, vendor, status, asOfDate, defaultPrompt,psTypes);
                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Inventory Summary Report",null,null,null );
                
                // To add grouping rows into the report
                ArrayList<String> groupColArray = new ArrayList<String>();
                String psTypesArray[] 	= psTypes.split(",");
                int pstypeCount  		= psTypesArray.length;
                
                for (int ps=0; ps < pstypeCount; ps++ )
                {
                    if ( psTypesArray[ps] != null && psTypesArray[ps].trim().length() > 0 )
                    {
                    	groupColArray.add(2+ps+"");
                    }
                }
                groupColArray.add(2+pstypeCount+"");
                groupColArray.add(3+pstypeCount+"");
                                
                DataDumpReportsHelper.groupWorkbook( workbook, 0, 3, 0, groupColArray );
                
                fileName = "inventorySummaryReport_" + DateUtil.getTimeStamp() ;
            }
            else if( "shipmentReportByDate".equalsIgnoreCase( action ) )
            {                   
                String processType      = request.getParameter( "prompt0" );
                String processstepIds   = request.getParameter( "prompt1" );
                String baseProductIds   = request.getParameter( "prompt2" );
                String vendor           = request.getParameter( "prompt3" );
                String fromDate         = request.getParameter( "prompt4" );
                String toDate           = request.getParameter( "prompt5" );
                String searchPartNo     = request.getParameter( "prompt6" );
                String category         = request.getParameter( "prompt7" );
                String status           = request.getParameter( "prompt8" );
                String reportFrom       = request.getParameter( "prompt9" );
                String reportFormat     = request.getParameter( "prompt10" );
                String defaultPrompt    = request.getParameter( "prompt11" );
                
                lotInfoList = DataDumpReportsDAO.getShipmentRecords ( null, processType, processstepIds, baseProductIds, vendor, fromDate, toDate, searchPartNo, category, status, reportFrom, reportFormat, defaultPrompt );

                workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Shipment Report", null,null,null );
                fileName = "ShipmentReport"+"_"+ DateUtil.getTimeStamp() ;

            }
            else if ("openPOReportExcel".equalsIgnoreCase(action) )
            {
                 String reportType   = request.getParameter( "reportType" );

                System.out.println("reportType = " + reportType);
                lotInfoList = DataDumpReportsDAO.getOpenPOPPVIPVReports ( null, reportType );
                if ("openPO".equalsIgnoreCase( reportType ) )
                {
                    ExcelColumnProperties colProps1 = new ExcelColumnProperties("PO Rate");
                    colProps1.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);

                    ExcelColumnProperties colProps2 = new ExcelColumnProperties("PO Amount");
                    colProps2.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    colProps2.setShowTotal(true);

                    List<ExcelColumnProperties> list = new ArrayList<ExcelColumnProperties>();
                    list.add(colProps1);
                    list.add(colProps2);

                    workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Open PO Report", null,null,list );
                    fileName = "OpenPOReport"+"_"+ DateUtil.getTimeStamp() ;

                }
                else
                {
                    ExcelColumnProperties colProps1 = new ExcelColumnProperties("Std Cost");
                    colProps1.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    ExcelColumnProperties colProps2 = new ExcelColumnProperties("PO Cost");
                    colProps2.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    ExcelColumnProperties colProps3 = new ExcelColumnProperties("Actual Cost");
                    colProps3.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    ExcelColumnProperties colProps4 = new ExcelColumnProperties("PPV/Wafer");
                    colProps4.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    ExcelColumnProperties colProps5 = new ExcelColumnProperties("IPV/Wafer");
                    colProps5.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    ExcelColumnProperties colProps6 = new ExcelColumnProperties("Total PPV");
                    colProps6.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    colProps6.setShowTotal(true);
                    ExcelColumnProperties colProps7 = new ExcelColumnProperties("Total IPV");
                    colProps7.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                    colProps7.setShowTotal(true);

                    List<ExcelColumnProperties> list = new ArrayList<ExcelColumnProperties>();
                    list.add(colProps1);list.add(colProps2);list.add(colProps3);list.add(colProps4);
                    list.add(colProps5);list.add(colProps6);list.add(colProps7);
                    
                    workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "PPV-IPV Report", null,null,list );
                    fileName = "PPV-IPV Report"+"_"+ DateUtil.getTimeStamp() ;

                }
            }
            ExcelUtils.generateExcelReport( workbook, fileName, response);
            /*filePath = request.getSession().getServletContext().getRealPath( ConfigManager.getDataDumpReportsFilePath() );
            boolean exists = ( new File( filePath ) ).exists();
            if ( !exists )
            {
                File file = new File( filePath );
                file.mkdirs();
            }*/

            /*fileOut = new FileOutputStream( filePath + "/" + fileName );
            if ( workbook != null )
            {
                try
                {
                    workbook.write( fileOut );
                    request.setAttribute ( "fileName", fileName );
                }
                catch ( Exception e )
                {
                    errors.put ( "Could not write excel file to disk", null );
                    e.printStackTrace();
                }
            }
            fileOut.close();*/

            /*ByteArrayOutputStream bos = null;
            try
            {
                bos = new ByteArrayOutputStream();
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName  + ";");
                if ( workbook != null )
                {
                    workbook.write( bos );
                    bos.writeTo( response.getOutputStream() );
                }
                response.getOutputStream().flush();
            }
            catch( Exception innerExcep )
            {
                String stackTrace = innerExcep.toString();
                if ( stackTrace.indexOf("socket write error") > -1 || stackTrace.indexOf("Socket closed") > -1 )
                {
                    System.out.println("## Export to Excel ClientAbortException ##");
                    //Logger.error( "## Export to Excel ClientAbortException ##", innerExcep );
                }
                else
                {
                    throw innerExcep;
                }
            }
            finally
            {
                try { bos.close(); } catch ( IOException ignore ) {}
                response.getOutputStream().close();
            }*/
        }
        catch ( Exception e)
        {
            errors.put ( "Could not generate excel file", null );
            e.printStackTrace();
        }
        return mapping.findForward( "reportView" );
    }
}
